//index.js
//获取应用实例
const app = getApp()

Page({
    data: {
        //判断小程序的API，回调，参数，组件等是否在当前版本可用。
        //unionid信息
        encryptedData:"",
        ivStr:"",
        //登录-加载判断
        userInfo: {},
        hasUserInfo: false,
        canIUse: wx.canIUse('button.open-type.getUserInfo'),
        owner:null,//老用户
        nothing:null,//新用户
        //授权页
        telVal:"",       //手机号
        Length:6,        //输入框个数
        isFocus:true,    //聚焦
        Value:"",        //输入的内容
        ispassword:false, //是否密文显示 true为密文， false为明文。
        //操作中心首页
    },
    onLoad: function () {
        // 登录模块
        var that = this;
        var user=wx.getStorageSync('user') || {};
        var userInfo=wx.getStorageSync('userInfo') || {};

        // wx.redirectTo({//调试内页
        //     url: '../controlAirconditioning/controlAirconditioning'
        // });
        that.isAuthUserInfo();

        if (app.globalData.userInfo) {
            this.setData({
                userInfo: app.globalData.userInfo,
                hasUserInfo: true
            })
        } else if (this.data.canIUse){
            // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
            // 所以此处加入 callback 以防止这种情况
            app.userInfoReadyCallback = res => {
                this.setData({
                    userInfo: res.userInfo,
                    hasUserInfo: true
                })
            }
        } else {
            // 在没有 open-type=getUserInfo 版本的兼容处理
            wx.getUserInfo({
                success: res => {
                    app.globalData.userInfo = res.userInfo
                    this.setData({
                        userInfo: res.userInfo,
                        hasUserInfo: true
                    })
                }
            })
        }
    },
    onShow:function(){
        var that =this;
        wx.getUserInfo({
            success: res => {
                //如果用户点击过授权，可以直接获取到信息
                console.log(res.userInfo)
                that.loginFuc()
            },
            fail: err => {
                //如果用户没有点击过授权，或者清除缓存，删除小程序，重新进入，会进入这里
                //然后你就可以进行你的操作，弹窗或者跳页面
                //跳页面推荐使用重定向 wx.redirectTo({})
                console.log(err.errMsg)
                that.setData({
                    nothing:null,
                    owner:true
                })
            }
        })
    },
    getUserInfo: function(e) {
        console.log(e)
        app.globalData.userInfo = e.detail.userInfo
        this.setData({
            userInfo: e.detail.userInfo,
            hasUserInfo: true
        })
    },
    //授权页
    telFuc:function(e){//绑定手机号
        var that = this;
        that.setData({//手机号传值
            telVal:e.detail.value,
        })
        if(that.data.telVal.length == 11&&that.data.Value.length !== 0){
            that.checkFuc();
        }
    },
    Focus(e){
        var that = this;
        var inputValue = e.detail.value;
        that.setData({
            Value:inputValue,
        })
        //超过五位数
        var num = inputValue.length;
        if(num == 6){
            this.checkFuc();
            // this.commitFuc(num);
        }
    },
    Tap(){
        var that = this;
        that.setData({
            isFocus:true,
        })
    },
    formSubmit(e){
        console.log(e.detail.value.password);
    },
    checkFuc:function(){//校验
        var that = this;
        var telVal = that.data.telVal;
        var verVal = that.data.Value;
        var phoneReg = !(/^1[34578][0-9]\d{4,8}$/.test(telVal));
        if(telVal == ''){
            app.openAlert("手机号不能为空！");
            return false;
        }else if(telVal.length < 11){
            app.openAlert("手机号少于11位！");
            return false;
        }else if(phoneReg){
            app.openAlert("手机号格式不正确！");
            return false;
        }else if(telVal.length == 11){
            if(verVal.length == 0){
                app.openAlert("授权码不能为空！");
                return false;
            }else if(verVal.length !== 6){
                app.openAlert("授权码格式不正确！");
                return false;
            }
        }
            that.commitFuc();
        },
    commitFuc:function(){//校验后提交
        var that = this;
        console.log(app.globalData.tokenSession);
        wx.request({
            // url:"http://192.168.4.6:8080/web-wxmp/bisUserAuthorizationRecord/queryBisUserAuthorizationRecordByToUserMobileOrAuthorizedCode",
            url: app.globalData.globalApi+"bisUserAuthorizationRecord/queryBisUserAuthorizationRecordByToUserMobileOrAuthorizedCode",//校验手机号验证码接口
            data:{
                toUserMobile:that.data.telVal,//手机号
                authorizedCode:that.data.Value//验证码
            },
            method: 'post', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
            dataType:'json',
            header: {
                "token-session": app.globalData.tokenSession, // 设置请求的header，写入返回token
                'experience-Pattern':app.globalData.experiencePattern// 是否为体验用户
            },
            success: function(res){
                var status = res.data.success;
                if(status){// 验证通过跳转控制首页
                    wx.redirectTo({
                        url: '../controlIndex/controlIndex'　　
                    })
                }else{
                    app.openAlert("授权码有误！");
                    return false;
                }
            },
            fail:function(res){
                app.openAlert("请求校验失败！");
                return false;
            }
        })
        // console.log(app.openAlert());
        // this.setData({//切换首页模块
        //     owner:true,
        //     nothing:false
        // })
    },
    //判断是否授权
    isAuthUserInfo: function () {//判断是否有获取用户信息的权限
        var that = this;// 可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.userInfo" 这个 scope
        wx.getSetting({
            success(res) {
                console.log(res.authSetting['scope.userInfo'])
                if (!res.authSetting['scope.userInfo']) {
                    wx.authorize({
                        scope: 'scope.userInfo',
                        success() {// 用户已经同意小程序获取用户信息
                            wx.getUserInfo();
                            that.getUserInfo();
                            res.authSetting = {
                                "scope.userInfo": true,
                                "scope.userLocation": true
                            }
                        },
                        fail(){//显示授权触发模块
                            that.setData({
                                nothing:null,
                                owner:true
                            })
                        }
                    })
                }else{
                    // that.loginFuc();
                }
            }
        })



    },
    loginFuc:function () {
        // if((!user.openid || (user.expires_in || Date.now()) < (Date.now() + 600))&&(!userInfo.nickName)){
        var that = this;
        wx.login({
            success: function(res){
                if(res.code) {
                    that.setData({
                        code: res.code,
                    });
                    wx.getUserInfo({//请求用户信息
                        success: function (res) {
                            that.setData({
                                encryptedData:res.encryptedData,
                                ivStr:res.iv
                            })
                        },
                        complete:function () {
                            that.sendLoginFuc();
                        }
                    });
                }else {
                    console.log('获取用户登录态失败！' + res.errMsg)
                }
            }
        });
        // }
    },
    sendLoginFuc:function(){
        var that = this;
        var posData = {
            code:that.data.code,
            encryptedData:that.data.encryptedData,
            ivStr:that.data.ivStr
        }
        var loginUrl=app.globalData.globalApi+"wechat/user/login"; //后端本地测试地址
        // var loginUrl='http://aiyitest.dev.linkeddr.com/smarthome-web-wxminiapp/wechat/user/login'; //后端外网测试地址地址
        // var l='https://api.weixin.qq.com/sns/jscode2session?appid='+d.appid+'&secret='+d.secret+'&js_code='+res.code+'&grant_type=authorization_code';     // 客户端直接获取oppenid ，暂不需要
        // var l='http://192.168.3.30:8083/wechat/user/login';
        // var l='http://localhost/server.php';//本地测试接口
        wx.request({//code与后端交换session key
            url: loginUrl,
            data: posData,
            // dataType:'json',
            method: 'post', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
            // header: {}, // 设置请求的 header
            success: function(res){
                console.log(res)
                // const obj={};
                // obj.openid=res.data.openid;
                // obj.expires_in=Date.now()+res.data.expires_in;
                // wx.setStorageSync('user', obj);//存储openid
                const isAdmin=res.data.data.isAdmin;//获取判断是否为管理员
                app.globalData.isAdmin= isAdmin; //存入全局
                const resData = res.data;
                const userCheck = resData.data.user_bind;

                if(userCheck == 'nothing'){//新用户显示授权界面
                    that.setData({
                        nothing:userCheck
                    });
                    wx.setNavigationBarTitle({
                        title: '输入授权码' //修改对应页面标题
                    });
                    console.log(that);
                }else if(userCheck == 'owner'){//老用户显示控制首页界面
                    wx.redirectTo({
                        url: '../controlIndex/controlIndex'　　// 直接跳转
                    });
                    console.log(that);
                }
                app.globalData.tokenSession = resData.data.WXAccessToken;//token写入全局
                // console.log(app.globalData.tokenSession);
                console.log(app.globalData.tokenSession);
            },
            fail:function (res){
                console.log(res);
            }
        });
    },
    bindGetUserInfo: function(e) {
        var that = this;
        console.log(e.detail.userInfo);
        if (e.detail.userInfo){
            //用户按了允许授权按钮
            that.getUserInfo(e);
            wx.getUserInfo({//请求用户信息
                success: function (res) {
                    that.loginFuc();//授权成功 调用登录接口
                }
            });
            that.setData({//显示首页判断模块
                owner:null
            });
        } else {
            //用户按了拒绝按钮
        }
    }
    //操作中心首页
});
